package com.hz.friends.group;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.ProgressCallback;
import com.avos.avoscloud.SaveCallback;
import com.hz.friends.activity.BigImageActivity;
import com.hz.friends.activity.EditUserInfosActivity;
import com.hz.friends.activity.GroupMembersActivity;
import com.hz.friends.activity.InfosInputActivty;
import com.hz.friends.activity.InviteFriendsActivity;
import com.hz.friends.activity.MaintabsActivity;
import com.hz.friends.activity.R;
import com.hz.friends.activity.SelectPhotoActivity;
import com.hz.friends.activity.UserInfosActivity;
import com.hz.friends.activity.SelectPhotoActivity.Callback;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.global.Global;
import com.hz.friends.location.LocationService;
import com.hz.friends.serverrequest.ALCCPEngine;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.serverrequest.ALCCPEngine.ALGroupType;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;

public class CreateGroupActivity extends SelectPhotoActivity implements
		View.OnClickListener {

	private LinearLayout layoutheard1;
	private LinearLayout layoutheard2;
	private int activitytype = 0; // 0：创建群 ,1:编辑群资料,2：查看群资料
	private FrameLayout layout_topimages;
	private ImageView imv_grouptype;
	private TextView txv_grouptype;
	private TextView txv_location;
	private TextView txv_groupname;
	private TextView txv_desc;
	private ImageView imv_heard;
	private final int INPUT_REQUEST = 11; // 输入页面跳转request
	private Button btn_submit;
	private Button btn_invite;
	private Button btn_dissolution;
	private Button btn_editok;
	private LinearLayout layout_viewgroup;
	private View viewgroup_divder;
	private AQuery aq;
	private TextView imbtn_bar_title;
	private ImageButton imbtn_bar_right;
	private LinearLayout include_menu;
	private Animation slidebotomein;
	private Animation slidebotomeout;
	private LinearLayout layout_location;
	private ImageView imv_location;
	private Animation cryclyanmim;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_creategroup);
		init();
		initViews();
		setViews();
	}

	@Override
	protected void init() {
		activitytype = getIntent().getIntExtra("activitytype", 0);
		aq = new AQuery(this);
		slidebotomein = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.slide_botome_in); // 从底部进动画
		slidebotomeout = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.slide_botome_out); // 从底部出动画

		cryclyanmim = AnimationUtils.loadAnimation(this,
				R.anim.anim_image_cycle);
		cryclyanmim.setInterpolator(new LinearInterpolator());

	}

	@Override
	protected void initViews() {
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_title.setText("Create Group");
		imbtn_bar_right.setVisibility(View.GONE);
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		imbtn_bar_left.setOnClickListener(this);
		imbtn_bar_right.setOnClickListener(this);
		layout_topimages = (FrameLayout) findViewById(R.id.layout_topimages); // 图片展示第一排
		layoutheard1 = (LinearLayout) findViewById(R.id.layoutheard1);// 图片展示第二排
		layoutheard2 = (LinearLayout) findViewById(R.id.layoutheard2);// 图片展示第二排
		LinearLayout layout_heard = (LinearLayout) findViewById(R.id.layout_heard);// 头像布局
		imv_heard = (ImageView) findViewById(R.id.imv_heard);// 头像
		txv_location = (TextView) findViewById(R.id.txv_location);// 地理位置
		// txv_refrest = (TextView) findViewById(R.id.txv_refrest);// 位置刷新
		layout_location = (LinearLayout) findViewById(R.id.layout_location);// 位置刷新
		imv_location = (ImageView) findViewById(R.id.imv_location);// 位置刷新
		LinearLayout layout_groupname = (LinearLayout) findViewById(R.id.layout_groupname);// 群名称布局
		txv_groupname = (TextView) findViewById(R.id.txv_groupname);// 群名称
		imv_grouptype = (ImageView) findViewById(R.id.imv_grouptype);// 群类别图标
		txv_grouptype = (TextView) findViewById(R.id.txv_grouptype);// 群类别名称
		LinearLayout layout_desc = (LinearLayout) findViewById(R.id.layout_desc);// 群描述布局
		viewgroup_divder = (View) findViewById(R.id.viewgroup_divder);// 【查看群资料】分割线
		layout_viewgroup = (LinearLayout) findViewById(R.id.layout_viewgroup);// 【查看群资料】预览群成员
		txv_desc = (TextView) findViewById(R.id.txv_desc);// 群描述1
		btn_submit = (Button) findViewById(R.id.btn_submit);// 【创建群】提交按钮
		btn_invite = (Button) findViewById(R.id.btn_invite);// 【查看群资料】邀请好友
		btn_dissolution = (Button) findViewById(R.id.btn_dissolution);// 【查看群资料】解散群
		btn_editok = (Button) findViewById(R.id.btn_editok);// 【编辑群资料】提交按钮
		include_menu = (LinearLayout) findViewById(R.id.include_menu); // 菜单布局
		TextView option1 = (TextView) include_menu.findViewById(R.id.option1); // option1
		TextView option2 = (TextView) include_menu.findViewById(R.id.option2); // option2
		TextView option3 = (TextView) include_menu.findViewById(R.id.option3); // option3

		layout_heard.setOnClickListener(this);
		layout_groupname.setOnClickListener(this);
		layout_desc.setOnClickListener(this);
		btn_submit.setOnClickListener(this);
		btn_invite.setOnClickListener(this);
		btn_dissolution.setOnClickListener(this);
		btn_editok.setOnClickListener(this);
		include_menu.setOnClickListener(this);
		option1.setOnClickListener(this);
		option2.setOnClickListener(this);
		option3.setOnClickListener(this);
		layout_location.setOnClickListener(this);
		layout_viewgroup.setOnClickListener(this);

	}

	@Override
	protected void setViews() {
		// 根据类别创建页面
		switch (activitytype) {
		case 0: // 创建群
			layout_topimages.setVisibility(View.GONE);
			viewgroup_divder.setVisibility(View.GONE);
			layout_viewgroup.setVisibility(View.GONE);
			btn_dissolution.setVisibility(View.GONE);
			btn_invite.setVisibility(View.GONE);
			btn_editok.setVisibility(View.GONE);
			break;
		case 1:// 编辑群
			layout_location.setVisibility(View.GONE);
			viewgroup_divder.setVisibility(View.GONE);
			layout_viewgroup.setVisibility(View.GONE);
			btn_dissolution.setVisibility(View.GONE);
			btn_invite.setVisibility(View.GONE);
			btn_submit.setVisibility(View.GONE);
			initData();
			imbtn_bar_title.setText("Edit Group");
			imbtn_bar_right.setVisibility(View.INVISIBLE);
			break;
		case 2: // 查看群
			layout_location.setVisibility(View.GONE);
			btn_submit.setVisibility(View.GONE);
			btn_editok.setVisibility(View.GONE);
			imbtn_bar_right.setImageResource(R.drawable.userinfo_edit);
			initData();
			break;

		default:
			break;
		}

		// 默认头像
		final int width = DensityUtil.dip2px(this, 70);
		final int stroke = DensityUtil.dip2px(this, 1);
		Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
		Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(this,
				crclebitmap, width, stroke, "#eeeeee");
		imv_heard.setImageBitmap(crclestrokebitmap);

		// 【创建群】设置群类别
		if (activitytype == 0) {
			int type = getIntent().getIntExtra("type", 1);
			switch (type) {
			case 1:
				imv_grouptype.setImageResource(R.drawable.btn_nearbytop_1);
				txv_grouptype.setText("Business");
				break;
			case 2:
				imv_grouptype.setImageResource(R.drawable.btn_nearbytop_2);
				txv_grouptype.setText("Food");
				break;
			case 3:
				imv_grouptype.setImageResource(R.drawable.btn_nearbytop_3);
				txv_grouptype.setText("News");
				break;
			case 4:
				imv_grouptype.setImageResource(R.drawable.btn_nearbytop_4);
				txv_grouptype.setText("Chat");
				break;
			case 5:
				imv_grouptype.setImageResource(R.drawable.btn_nearbytop_5);
				txv_grouptype.setText("Entertainment");
				break;
			default:
				break;
			}
		}

	}

	@Override
	protected void initEvents() {

	}

	private void initData() {
		AVObject groupdata = CustomApplication.getInstance().currgroup;
		final String heardurl = groupdata.getString("coverURL");
		String place = groupdata.getString("place");
		String name = groupdata.getString("name");
		String desc = groupdata.getString("declared");
		int type = groupdata.getInt("type");

		// 默认头像
		final int width = DensityUtil.dip2px(this, 70);
		final int stroke = DensityUtil.dip2px(this, 1);
		Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
		Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(this,
				crclebitmap, width, stroke, "#eeeeee");
		imv_heard.setImageBitmap(crclestrokebitmap);
		// 头像
		aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
			@Override
			public void callback(String url, Bitmap bitmap, AjaxStatus status) {
				Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(
						getApplicationContext(), bitmap, width, stroke,
						"#eeeeee");
				imv_heard.setImageBitmap(mbitmap);
			}
		});

		txv_location.setText(place);
		txv_groupname.setText(name);
		txv_desc.setText(desc);
		if (activitytype != 0)
			imbtn_bar_title.setText(name);
		if (type == ALCCPEngine.ALGroupType.ALGroupTypeOfBusiness.get_value()) {
			imv_grouptype.setImageResource(R.drawable.btn_nearbytop_1);
			txv_grouptype.setText("Business");
		} else if (type == ALCCPEngine.ALGroupType.ALGroupTypeOfChat
				.get_value()) {
			imv_grouptype.setImageResource(R.drawable.btn_nearbytop_4);
			txv_grouptype.setText("Chat");
		} else if (type == ALCCPEngine.ALGroupType.ALGroupTypeOfEntertainMent
				.get_value()) {
			imv_grouptype.setImageResource(R.drawable.btn_nearbytop_5);
			txv_grouptype.setText("Entertainment");
		} else if (type == ALCCPEngine.ALGroupType.ALGroupTypeOfFood
				.get_value()) {
			imv_grouptype.setImageResource(R.drawable.btn_nearbytop_2);
			txv_grouptype.setText("Food");

		} else if (type == ALCCPEngine.ALGroupType.ALGroupTypeOfNews
				.get_value()) {
			imv_grouptype.setImageResource(R.drawable.btn_nearbytop_3);
			txv_grouptype.setText("News");
		}
		if (activitytype == 2) {
			//判断群的创建者
			AVUser create = groupdata.getAVUser("creater");
			if (AVUser.getCurrentUser().getObjectId()
					.equals(create.getObjectId())) {//创建者
				imbtn_bar_right.setVisibility(View.VISIBLE);
				btn_dissolution.setVisibility(View.VISIBLE);
			} else {//other
				imbtn_bar_right.setVisibility(View.INVISIBLE);
				btn_dissolution.setVisibility(View.INVISIBLE);

			}
		}

		// 获取顶部图片
		ALUserEngine.defauleEngine().getGroupAlbum(groupdata, 8,
				new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "getGroupAlbum  object：" + object
								+ "  avexception:" + avexception);
						if (avexception == null) {
							if (object != null && object instanceof List) {
								if (activitytype == 2)// 查看群资料
									addTopImages((List<AVObject>) object);
								if (activitytype == 1) {// 编辑群资料
									picpaths.addAll((List<AVObject>) object);
									addTopImages();
								}
							}
						} else {
							avexception.printStackTrace();
						}
					}
				});

	}

	/**
	 * 【查看群资料】填充顶部图片数据
	 */
	private void addTopImages(List<AVObject> piclist) {
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int mScreenWidth = metric.widthPixels;
		int offset = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 11 * 2 + 6 * 3, getResources()
						.getDisplayMetrics());
		int rightmargin = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 6, getResources()
						.getDisplayMetrics());
		final int radius = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 6, getResources()
						.getDisplayMetrics());
		final int width = (mScreenWidth - offset) / 4;
		// Bitmap bitmap = BitmapUtils.createRoundConerImage(BitmapFactory
		// .decodeResource(getResources(), R.drawable.test_pic5), width,
		// radius);
		for (int i = 0; i < piclist.size(); i++) {
			final String url = piclist.get(i).getString("url");
			final ImageView mimageview = new ImageView(this);
			// mimageview.setImageResource(R.drawable.test_pic5);
			// mimageview.setImageBitmap(bitmap);
			mimageview.setScaleType(ScaleType.FIT_CENTER);
			mimageview.setBackgroundResource(R.drawable.shape_userinfo_pic_bj);
			aq.id(mimageview).image(url, true, true, 0, 0,
					new BitmapAjaxCallback() {
						protected void callback(String url, ImageView iv,
								Bitmap bm, AjaxStatus status) {
							if (bm != null) {
								Bitmap bitmap = BitmapUtils
										.createRoundConerImage(bm, width,
												radius);
								iv.setImageBitmap(bitmap);
								iv.setBackgroundColor(Color.TRANSPARENT);
							}
						};
					});
			LinearLayout.LayoutParams lap = new LinearLayout.LayoutParams(
					width, width);
			if (i != 3 && i != 8)
				lap.rightMargin = rightmargin;
			mimageview.setLayoutParams(lap);
			if (i <= 3)
				layoutheard1.addView(mimageview);
			else
				layoutheard2.addView(mimageview);
			mimageview.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent largeintent = new Intent(CreateGroupActivity.this,
							BigImageActivity.class);
					largeintent.putExtra("imageUrl", url);
					startActivity(largeintent);
				}
			});
		}

	}

	private List picpaths = new ArrayList(); // 顶部图片数据源
	private ArrayList<AVObject> delepiclist = new ArrayList<AVObject>(); // 顶部图片数据源

	/**
	 * 【编辑群资料】添加顶部图片
	 */
	private void addTopImages() {
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int mScreenWidth = metric.widthPixels;
		int offset = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 11 * 2 + 6 * 3, getResources()
						.getDisplayMetrics());
		final int rightmargin = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 6, getResources()
						.getDisplayMetrics());
		final int radius = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 6, getResources()
						.getDisplayMetrics());
		final int width = (mScreenWidth - offset) / 4;

		layoutheard1.removeAllViews();
		layoutheard2.removeAllViews();
		// 添加图片
		for (int i = 0; i < picpaths.size(); i++) {
			Object picpath = picpaths.get(i);
			final ImageView mImageView = new ImageView(CreateGroupActivity.this);
			mImageView.setTag(picpath);
			mImageView.setScaleType(ScaleType.FIT_XY);
			if (picpath instanceof String) {// 刚添加的
				Bitmap bitmap = BitmapUtils.createRoundConerImage(
						BitmapFactory.decodeFile((String) picpath), width,
						radius);
				mImageView.setImageBitmap(bitmap);
			}
			if (picpath instanceof AVObject) {// 网络上的
				String url = ((AVObject) picpath).getString("url");
				// aq.id(mImageView).image(url, true, true);
				aq.id(mImageView).image(url, true, true, 0, 0,
						new BitmapAjaxCallback() {
							protected void callback(String url, ImageView iv,
									Bitmap bm, AjaxStatus status) {
								if (bm != null) {
									Bitmap bitmap = BitmapUtils
											.createRoundConerImage(bm, width,
													radius);
									iv.setImageBitmap(bitmap);
									iv.setBackgroundColor(Color.TRANSPARENT);
								}
							};
						});

			}

			LinearLayout.LayoutParams lap = new LinearLayout.LayoutParams(
					width, width);
			if (i != 4)
				lap.rightMargin = rightmargin;
			mImageView.setLayoutParams(lap);
			if (i < 4) {
				layoutheard1.addView(mImageView);
			} else {
				layoutheard2.addView(mImageView);
			}
			final int postion = i;
			mImageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					include_menu.startAnimation(slidebotomein);
					include_menu.setVisibility(View.VISIBLE);
					include_menu.setTag(postion);
				}
			});

		}

		// 添加按钮
		final ImageView addImageView = new ImageView(this);
		addImageView.setImageResource(R.drawable.userinfo_addimage);
		addImageView.setScaleType(ScaleType.FIT_CENTER);
		LinearLayout.LayoutParams lap = new LinearLayout.LayoutParams(width,
				width);
		addImageView.setLayoutParams(lap);
		addImageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setIssmallpic(false);
				getPhoto("图片");
				setMcallback(new Callback() {
					@Override
					public void dosomething() {
						File file = getLargepic_file();
						if (file == null)
							return;
						picpaths.add(file.getAbsolutePath());
						addTopImages();
					}
				});
			}
		});

		if (picpaths.size() < 4)
			layoutheard1.addView(addImageView);
		else if (picpaths.size() < 8)
			layoutheard2.addView(addImageView);

	}

	int uploadpiccount = 0; // 统计图片上传
	int waitcount = 0; // 删除图片加1 上传图片加1 编辑资料加1 3取消waitdialog

	// 上传图片
	private void uploadpics() {
		final ArrayList<AVObject> uploadpics = new ArrayList<AVObject>();// 需要上传的图片
		final ArrayList<String> uploadpiclist = new ArrayList<String>();// 需要上传的图片

		// 过滤需要上传的图片
		for (int i = 0; i < picpaths.size(); i++) {
			Object obj = picpaths.get(i);
			if (obj instanceof String) {
				uploadpiclist.add((String) obj);
			}
		}

		// 上传
		for (int i = 0; i < uploadpiclist.size(); i++) {
			String filepath = uploadpiclist.get(i);
			try {
				final AVFile file = AVFile.withAbsoluteLocalPath(
						System.currentTimeMillis() + ".jpg", filepath);
				file.saveInBackground(new SaveCallback() {

					@Override
					public void done(AVException e) {
						if (e != null) {
							e.printStackTrace();
							uploadpiccount++;
							isuploadPics(uploadpiclist.size(), uploadpics);
						} else {// 上传文件成功
								// 创建photo
							ALUserEngine.defauleEngine().createPhoto(
									file.getUrl(), null, new CallBack() {

										@Override
										public void done(Object object,
												AVException avexception) {
											uploadpiccount++;
											if (avexception != null) {
												avexception.printStackTrace();
											} else {// 创建成功
												if (object != null
														&& object instanceof AVObject)
													uploadpics
															.add((AVObject) object);
											}
											isuploadPics(uploadpiclist.size(),
													uploadpics);

										}
									});
						}
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
				uploadpiccount++;
				isuploadPics(uploadpiclist.size(), uploadpics);
			}

		}
		if (uploadpiclist.size() == 0)
			isuploadPics(uploadpiclist.size(), uploadpics);

	}

	// 正式上传照片
	private void isuploadPics(int count, ArrayList<AVObject> photos) {
		if (uploadpiccount == count) {
			MLog.i(TAG, "上传照片数:" + count + " 实际上传数:" + photos.size());
			if (!photos.isEmpty()) {
				ALCCPEngine.defauleEngine().updateAlbumOfGroup(CustomApplication.getInstance().currgroup,photos,
						new CallBack() {

							@Override
							public void done(Object object,
									AVException avexception) {
								if (avexception != null) {// 失败
									avexception.printStackTrace();
								} else {// 成功

								}
								mhandler.sendEmptyMessage(1);
							}
						});
			} else {
				mhandler.sendEmptyMessage(1);
			}

		}
	}

	// 删除网络图片
	private void deletePics() {
		MLog.i(TAG, "删除照片数:" + delepiclist.size());
		if (!delepiclist.isEmpty()) {
			ALCCPEngine.defauleEngine().deleteAlbumOfGroup(CustomApplication.getInstance().currgroup,delepiclist,
					new CallBack() {

						@Override
						public void done(Object object, AVException avexception) {
							if (avexception != null) {// 失败
								avexception.printStackTrace();
							} else {// 成功

							}
							mhandler.sendEmptyMessage(1);
						}
					});
		} else {
			mhandler.sendEmptyMessage(1);
		}

	}

	private Handler mhandler = new Handler() {
		private String submitresult;

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				waitcount++;
				if (msg.obj != null)
					submitresult = (String) msg.obj;
				 if (waitcount == 3) {
					cancleWaitDialog();
					if (!TextUtils.isEmpty(submitresult)) {
						showToast(submitresult);
					}

					if ("编辑群资料成功".equals(submitresult)) {
						finish();
					}
				}
				break;
			case 3:// 处理定位
				if (imv_location.getTag() != null) {
					showToast("定位失败,请尝试重新定位");
					Intent locationintent = new Intent(
							CreateGroupActivity.this, LocationService.class);
					stopService(locationintent);
					imv_location.clearAnimation();
					imv_location.setTag(null);
				}
				break;
			default:
				break;
			}

		};
	};

	private TextView inputTextView = null; // 输入textview
	private LocationReciverBroad mlocationReciverBroad;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imbtn_bar_left:
			finish();
			break;
		case R.id.imbtn_bar_right:
			Intent intent = new Intent(this, CreateGroupActivity.class);
			intent.putExtra("activitytype", 1);
			startActivity(intent);
			finish();
			break;
		case R.id.layout_heard:// 头像

			if (activitytype == 0) {
				setIssmallpic(false);
				takePhoto();
			} else if (activitytype == 1) {
				getPhoto("头像");
				setIssmallpic(true);
			} else {
				AVObject groupdata = CustomApplication.getInstance().currgroup;
				final String heardurl = groupdata.getString("coverURL");
				Intent largeintent = new Intent(CreateGroupActivity.this,
						BigImageActivity.class);
				largeintent.putExtra("imageUrl", heardurl);
				startActivity(largeintent);
				return;
			}
			final int size = DensityUtil.dip2px(this, 70);
			final int stroke = DensityUtil.dip2px(this, 2);
			setSize(size);
			setMcallback(new Callback() {
				@Override
				public void dosomething() {
					File file = getLargepic_file();
					if (file == null)
						return;
					Bitmap bitmap = BitmapFactory.decodeFile(file
							.getAbsolutePath());
					Bitmap mbtimap = BitmapUtils.getCircleStrokbitmap(
							getApplicationContext(), bitmap, size, stroke,
							"#c4c4c5");
					imv_heard.setImageBitmap(mbtimap);
//					showToast(file.getAbsolutePath());
					imv_heard.setTag(file.getAbsolutePath());
					bitmap.recycle();
				}
			});

			break;
		case R.id.layout_groupname:// 群名称
			if (activitytype == 2)
				return;
			Intent groupintent = new Intent(this, InfosInputActivty.class);
			groupintent.putExtra("TitleMessage", "Group Name");
			groupintent.putExtra("text", txv_groupname.getText().toString());
			groupintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(groupintent, INPUT_REQUEST);
			inputTextView = txv_groupname;
			break;
		case R.id.layout_desc:// 群描述
			if (activitytype == 2)
				return;
			Intent descintent = new Intent(this, InfosInputActivty.class);
			descintent.putExtra("TitleMessage", "Group describe");
			descintent.putExtra("text", txv_desc.getText().toString());
			descintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(descintent, INPUT_REQUEST);
			inputTextView = txv_desc;

			break;
		case R.id.btn_submit:
			sumbimt();
			break;
		case R.id.btn_editok:
			waitcount = 0;
			editGroup(null);
			break;
		case R.id.btn_dissolution:
			dissoluGroup();
			break;
		case R.id.btn_invite:
			Intent inviteIntent =new Intent(this, InviteFriendsActivity.class);
			startActivity(inviteIntent);
			break;
		case R.id.include_menu:// menu界面
			include_menu.startAnimation(slidebotomeout);
			include_menu.setVisibility(View.GONE);
			break;
		case R.id.option1:// 查看
			include_menu.startAnimation(slidebotomeout);
			include_menu.setVisibility(View.GONE);
			Object tag = include_menu.getTag();
			if (tag != null && tag instanceof Integer) {
				Intent largeintent = new Intent(this, BigImageActivity.class);

				int index = (Integer) tag;
				Object path = picpaths.get(index);
				if (path instanceof String) {
					largeintent.putExtra("imagePath", (String) path);
				}
				if (path instanceof AVObject) {
					largeintent.putExtra("imageUrl",
							((AVObject) path).getString("url"));
				}
				startActivity(largeintent);
			}
			break;
		case R.id.option2:// 删除
			include_menu.startAnimation(slidebotomeout);
			include_menu.setVisibility(View.GONE);
			Object deletetag = include_menu.getTag();
			if (deletetag != null && deletetag instanceof Integer) {
				int index = (Integer) deletetag;
				if (picpaths.get(index) instanceof AVObject) { // 保存需删除的网络图片
					delepiclist.add((AVObject) picpaths.get(index));
				}
				picpaths.remove(index);
				addTopImages();
			}
			break;
		case R.id.option3:// 取消
			include_menu.startAnimation(slidebotomeout);
			include_menu.setVisibility(View.GONE);
			break;
		case R.id.layout_location:// 定位
			Intent locationintent = new Intent(this, LocationService.class);
			if (imv_location.getTag() == null) {// 开始
				startService(locationintent);
				imv_location.startAnimation(cryclyanmim);
				imv_location.setTag("1");
				// 超时处理
				mhandler.removeMessages(3);
				mhandler.sendEmptyMessageDelayed(3, 1000 * 100);
			} else {// 停止
				stopService(locationintent);
				imv_location.clearAnimation();
				imv_location.setTag(null);
			}
          break;
		case R.id.layout_viewgroup:
			Intent viewgroupintent = new Intent(this, GroupMembersActivity.class);
			startActivity(viewgroupintent);
			break;
		default:
			break;
		}
	}

	// 创建群
	private void sumbimt() {
		if (imv_heard.getTag() == null) {
			showToast("请设置群头像");
			return;
		}
		if (txv_groupname.getText().toString().trim().length() == 0) {
			showToast("请设置群名称");
			return;
		}
		
		if (txv_location.getText().toString().trim().length() == 0) {
			showToast("请设置位置");
			return;
		}
		
		final ALGroupType groupType;
		int type = getIntent().getIntExtra("type", 1);

		if (type == ALGroupType.ALGroupTypeOfBusiness.get_value()) {
			groupType = ALGroupType.ALGroupTypeOfBusiness;
		} else if (type == ALGroupType.ALGroupTypeOfFood.get_value()) {
			groupType = ALGroupType.ALGroupTypeOfFood;
		} else if (type == ALGroupType.ALGroupTypeOfNews.get_value()) {
			groupType = ALGroupType.ALGroupTypeOfNews;
		} else if (type == ALGroupType.ALGroupTypeOfChat.get_value()) {
			groupType = ALGroupType.ALGroupTypeOfChat;
		} else {
			groupType = ALGroupType.ALGroupTypeOfEntertainMent;

		}
		createWiatDialog("加载中");
		final double[] localarr =  (double[]) txv_location.getTag();
		try {
			final AVFile file = AVFile.withAbsoluteLocalPath(
					System.currentTimeMillis() + ".jpg",
					(String) imv_heard.getTag());
			file.saveInBackground(new SaveCallback() {

				@Override
				public void done(AVException arg0) {
					if (arg0 != null) {
						cancleWaitDialog();
						arg0.printStackTrace();
						showToast("创建群失败");
					} else {
						ALCCPEngine.defauleEngine().createGroup(
								txv_groupname.getText().toString().trim(),
								file.getUrl(), groupType,
								txv_desc.getText().toString().trim(),
								localarr[0], localarr[1], 0, txv_location.getText().toString().trim(), false,
								new CallBack() {

									@Override
									public void done(Object object,
											AVException avexception) {
										MLog.i(TAG, "createGroup object:"
												+ object + "  avexception:"
												+ avexception);
										cancleWaitDialog();
										if (avexception == null) {
											showToast(txv_groupname.getText()
													.toString().trim()
													+ "群创建成功");
											finish();
										} else {
											avexception.printStackTrace();
											showToast("创建群失败");
										}
									}
								});

					}

				}
			});
		} catch (Exception e) {
			cancleWaitDialog();
			e.printStackTrace();
			showToast("创建群失败");
		}

	}

	// 编辑群
	private void editGroup(String heardurl) {
		if (waitcount > 3){
			cancleWaitDialog();
			showToast("编辑资料失败");
			return;
		}
		final ALGroupType groupType;
		int type = getIntent().getIntExtra("type", 1);

		if (type == ALGroupType.ALGroupTypeOfBusiness.get_value()) {
			groupType = ALGroupType.ALGroupTypeOfBusiness;
		} else if (type == ALGroupType.ALGroupTypeOfFood.get_value()) {
			groupType = ALGroupType.ALGroupTypeOfFood;
		} else if (type == ALGroupType.ALGroupTypeOfNews.get_value()) {
			groupType = ALGroupType.ALGroupTypeOfNews;
		} else if (type == ALGroupType.ALGroupTypeOfChat.get_value()) {
			groupType = ALGroupType.ALGroupTypeOfChat;
		} else {
			groupType = ALGroupType.ALGroupTypeOfEntertainMent;

		}
		createWiatDialog("加载中");
		if (imv_heard.getTag() != null) {
			try {
				final AVFile file = AVFile.withAbsoluteLocalPath(
						System.currentTimeMillis() + ".jpg",
						(String) imv_heard.getTag());
				file.saveInBackground(new SaveCallback() {

					@Override
					public void done(AVException arg0) {
						if (arg0 == null) {
							editGroup(file.getUrl());
							imv_heard.setTag(null);
						} else {
							arg0.printStackTrace();
							waitcount = 2;
							Message msg = mhandler.obtainMessage(1, "编辑资料失败");
							mhandler.sendMessage(msg);
						}
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
				waitcount = 2;
				Message msg = mhandler.obtainMessage(1, "编辑资料失败");
				mhandler.sendMessage(msg);
			}
			return;
		}

		ALCCPEngine.defauleEngine().updateGroup(
				CustomApplication.getInstance().currgroup,
				txv_groupname.getText().toString().trim(),
				heardurl, null, groupType,
				txv_desc.getText().toString().trim(), false, new CallBack() {
					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "createGroup object:" + object
								+ "  avexception:" + avexception);
						cancleWaitDialog();
						if (avexception == null) {
							Message msg = mhandler.obtainMessage(1, "编辑群资料成功");
							mhandler.sendMessage(msg);
						} else {
							avexception.printStackTrace();
							Message msg = mhandler.obtainMessage(1, "编辑资料失败");
							mhandler.sendMessage(msg);
						}
					}

				});
		 uploadpics();
		 deletePics();
	}

	private void dissoluGroup() {
		ALCCPEngine.defauleEngine().destroyGroup(
				CustomApplication.getInstance().currgroup, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i("MyTag", "destroyGroup  Object:" + object
								+ " avexception:" + avexception);
						if (avexception == null) {
							showToast("解散群成功");
						} else {
							avexception.printStackTrace();
						}
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null)
			return;
		if (requestCode == INPUT_REQUEST) {// 输入\语言
			String text = data.getStringExtra("text");
			boolean ischange = data.getBooleanExtra("ischange", false);
			if (inputTextView != null && ischange)
				inputTextView.setText(text);
		}

	}

	
    @Override
   protected void onResume() {
    	super.onResume();
    	//生成广播处理   
    	mlocationReciverBroad = new LocationReciverBroad();   
    	//实例化过滤器并设置要过滤的广播   
    	IntentFilter intentFilter = new IntentFilter(Global.LOCAT_ACTION); 
    	//注册广播   
    	 registerReceiver(mlocationReciverBroad, intentFilter);  
   }
    
   @Override
   protected void onPause() {
   	super.onPause();
   	 Intent locationintent = new Intent(CreateGroupActivity.this, LocationService.class);
		 stopService(locationintent);
   	unregisterReceiver(mlocationReciverBroad);
   }
	
   class LocationReciverBroad extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			MLog.i(TAG, "====reciver location brocats");
			double lat = intent.getDoubleExtra("lat", 0);
			double lon = intent.getDoubleExtra("lon", 0);
			String address = intent.getStringExtra("address");
			if("not_open_set".equals(address) && imv_location.getTag() != null){
				showToast("请打开Gps定位");
				 Intent locationintent = new Intent(CreateGroupActivity.this, LocationService.class);
				 stopService(locationintent);
				 imv_location.setTag(null);
					imv_location.clearAnimation();

	             return;
			}
			
		   if(!TextUtils.isEmpty(address)&& imv_location.getTag() != null){
				showToast("定位成功");
				 Intent locationintent = new Intent(CreateGroupActivity.this, LocationService.class);
				 stopService(locationintent);
					imv_location.clearAnimation();
				 imv_location.setTag(null);
	             txv_location.setText(address);
	             double[] intarr = new double[2];
	             intarr[0] = lat;
	             intarr[1] = lon;
	             txv_location.setTag(intarr);
	             
//	             //上传经纬度
//	             ALUserEngine.defauleEngine().updateLocation(lat, lon, address, new CallBack() {
//					
//					@Override
//					public void done(Object object, AVException avexception) {
//                    						
//					}
//				});
	             return;
			
		   }	
		}
   	
   }
}
